package com.sakura.system.controller.gldctroller.console;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.sakura.system.coommon.Result;
import com.sakura.system.entity.Params;
import com.sakura.system.entity.gld.User;
import com.sakura.system.exception.BusinessErrorException;
import com.sakura.system.service.impl.gldimpl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * gld
 * 2024-3-15
 * 后台用户操作
 */

@Slf4j
//解决跨域问题
@CrossOrigin
@RestController
@RequestMapping("${app.router.url}"+"/user")
public class UserController {
    @Autowired
    private UserServiceImpl service;

    /**
     *
     * @return
     */
    @GetMapping("/start")
    public Result start(){
        return Result.success("hdhdshdukslsksj");
    }

    @GetMapping("/getuser")
    public Result getUser(){
//        return new User1(12344,"赞赏", "1234567890","女", 17, "124364747");
        List<User> user = service.getUser();
        return Result.success(user);
    }

    @GetMapping("/search")
    public Result fibdBySearch(Params params){
//        log.info(params.toString());
        PageInfo<User> userPageInfo = service.fibdBySearch(params);
        return Result.success(userPageInfo);
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user){
        if (user.getId() != null){
            service.update(user);
        } else {
            service.add(user);
        }

        return Result.success();
    }

    @DeleteMapping("/{id}")
//    public Result delete(@PathVariable String id){
    public Result delete(@RequestBody String id){
//        log.info(id);
        service.delete(id);
        return Result.success();
    }
    @PutMapping("/delBatch")
    public Result delBatch(@RequestBody List<User> list){
        for (User user:list){
            service.delete(user.getId());
        }
        return Result.success();
    }


//    批量导出
    @GetMapping("/export")
    public Result exp(HttpServletResponse response) throws IOException {

        // 1,从数据库查询数据
        // 2,遍历每一条数据,封装到map
        // 3,创建一个excelwriter,把list数据用writer写出来
        List<User> listUser = service.findAll();
//        log.info("数据打印:");
//        log.info(listUser.toString());
        if (CollectionUtil.isEmpty(listUser)){
            throw new BusinessErrorException("未找到数据!");
        }
        List<Map<String,Object>> list = new ArrayList<>(listUser.size());
        for (User user : listUser) {
            Map<String,Object> map = new HashMap<>();
            map.put("用户名",user.getUsername());
            map.put("密码",user.getPassword());
            map.put("年龄",user.getAge());
            map.put("性别",user.getSex());
            map.put("电话",user.getPhone());

            list.add(map);
        }

        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list,true);
//        log.info(list.toString());

//        下载
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        type.xlsx  文件名称
        response.setHeader("Content-Disposition","attachment;filename=User1.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        IoUtil.close(System.out);

        return Result.success();
    }

//    批量导入
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
//        List<User1> typeList = ExcelUtil.getReader(file.getInputStream()).readAll(Type.class);
        List<User> typeList = ExcelUtil.getReader(file.getInputStream()).readAll(User.class);
        if (!CollectionUtil.isEmpty(typeList)){
            for (User user:typeList){
                try {
                    service.add(user);
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        return Result.success();
    }



}
